package xj.graph2d.app.prop;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JToggleButton;
import javax.swing.SwingConstants;

import xj.graph2d.BoxGroup;
import xj.graph2d.Command;
import xj.graph2d.DrawCanvas;
import xj.graph2d.DrawShape;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.TextShape;
import xj.graph2d.command.AlignmentCommand;

public class AlignmentListener extends AttrListener implements ActionListener {

  public void actionPerformed(ActionEvent e) {
    if (e != null) {
      Object src = e.getSource();
      if (src != null && src instanceof JToggleButton) {
	JToggleButton b = (JToggleButton) src;
	SimpleDrawView view = main.getView();
	SimpleDrawDocument doc = main.getDoc();
	String cmd = b.getActionCommand();
	int alignment = -1;
	if ("AlignLeft".equals(cmd)) {
	  alignment = SwingConstants.LEFT;
	} else if ("AlignCenter".equals(cmd)) {
	  alignment = SwingConstants.CENTER;
	} else if ("AlignRight".equals(cmd)) {
	  alignment = SwingConstants.RIGHT;
	}

	if (updateSystemAttr) {
	  // update system alignment setting
	  view.setAlignment(alignment);
	}

	BoxGroup box = null;
	DrawShape shape = doc.getSelectedShape();
	if (shape instanceof TextShape) {
	  DrawShape parent = shape.getParent();
	  if (parent instanceof BoxGroup) {
	    box = (BoxGroup) parent;
	  }
	} else if (shape instanceof BoxGroup) {
	  box = (BoxGroup) shape;
	}

	if (box != null && alignment != -1) {
	  Command command = new AlignmentCommand(view, doc, box);
	  doc.addCommand(command);

	  box.setAlignment(alignment);
	  box.align();
	  DrawCanvas canvas = view.getCanvas();
	  canvas.repaintShape(box, true);
	}
      }
    }
  }

}
